﻿using KongMing.WebTools.Common;
using KongMing.WebTools.Models;

namespace KongMing.WebTools.Service
{
    public class DataFormat
    {
        public static void FixOrmModelData(OrmModel table)
        {
            table.SqlTableName = string.IsNullOrWhiteSpace(table.SqlTableName) ? table.TableName : table.SqlTableName;
            if (!string.IsNullOrWhiteSpace(table.BaseEntityName) && table.WithBaseFields)
            {
                table.Fields.AddRange(new List<Field>(){
                    new Field(){ FieldName = "CreateTime", IsBaseField = true, DataType = SqlType.DateTime },
                    new Field(){ FieldName = "CreateUserId", IsBaseField = true,DataType = SqlType.Varchar, Length = "50" },
                    new Field(){ FieldName = "CreateUserName", IsBaseField = true, Length = "50" },
                    new Field(){ FieldName = "ChangeTime", IsBaseField = true, DataType = SqlType.DateTime, IsNullable = true },
                    new Field(){ FieldName = "ChangeUserId", IsBaseField = true,DataType = SqlType.Varchar, Length = "50", IsNullable = true },
                    new Field(){ FieldName = "ChangeUserName", IsBaseField = true, Length = "50", IsNullable = true },
                });
            }
            foreach (var field in table.Fields)
            {
                if (field.DataType == "varchar" || field.DataType == "nvarchar")
                    field.Length = string.IsNullOrWhiteSpace(field.Length) ? "50" : field.Length;

                field.IsNullable = field.IsPrimaryKey ? false : field.IsNullable;
                field.IsIdentity = field.DataType == SqlType.Int ? field.IsIdentity : false;
                field.SqlFieldName = table.SqlFieldSplitWords ? Tools.SplitWords(field.FieldName) : field.FieldName;
                field.SqlFieldName = table.SqlFieldLowerCase ? field.SqlFieldName.ToLower() : field.SqlFieldName;
                field.SqlFieldName = (string.IsNullOrWhiteSpace(table.SqlFieldPreFix) ? "" : table.SqlFieldPreFix) + field.SqlFieldName;
                field.SqlFieldType = Tools.FixSqlDataType(field.DataType, field.Length);
                field.CSharpFieldType = Tools.SqlTypeToCsType(field);
                Tools.FixSqlDefaultValue(field);
                if (table.CsEntityWithDefalueValue)
                    Tools.FixCSharpDefaultValue(field);
            }
        }
    }
}
